package com.yonyou.iuap.shiro;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import com.yonyou.iuap.base.intf.IUserAdminService;
import com.yonyou.iuap.base.vo.CtxEnvVO;
import com.yonyou.iuap.base.vo.UserVO;

public class ShellShiroDbRealm extends AuthorizingRealm {
	@Autowired
	private IUserAdminService iuser;
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		// TODO 自动生成的方法存根
		return null;
	}
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken arg0) throws AuthenticationException {
		ShellUserToken token = (ShellUserToken) arg0;
		CtxEnvVO ce = new CtxEnvVO();
		if(StringUtils.isEmpty(token.getUsername())){
			throw new AuthenticationException("用户名不能为空!");
		}
		if(StringUtils.isEmpty(token.getPassword())){
			throw new AuthenticationException("密码不能为空!");
		}
		//查询用户信息
		UserVO uservo = getUserVOByName(token.getUsername());
		if(uservo!=null){
			ce.setUser(uservo);
			ce.setPk_user(uservo.getPk_user());
			ce.setUser_name(uservo.getUser_name());
//			String encryptedPassWord = new String(token.getPassword());
//		    encryptedPassWord = encryptedPassWord.replace("_encrypted", "");
//		    String passWord = RSAUtils.decryptStringByJs(encryptedPassWord);
//		    byte[] hashPassword = Digests.sha1(passWord.getBytes(), Encodes.decodeHex(uservo.getSalt()), HASH_INTERATIONS);
//		    String checkPwd = Encodes.encodeHex(hashPassword);
//		    // 将密码按照加密算法进行加密之后，存储到token
//		    token.setPassword(checkPwd.toCharArray());
//		    byte[] salt = Encodes.decodeHex(user.getSalt());
//		    return new SimpleAuthenticationInfo(new ShiroUser(user.getId(), user.getLoginName(), user.getName()),
//		    		user.getPassword(), ByteSource.Util.bytes(salt), getName());

			return new SimpleAuthenticationInfo(uservo.getUser_name(),uservo.getPassword(),"");
		}else{
			throw new AuthenticationException("未查询到用户信息!");
		}
	}
	private UserVO getUserVOByName(String name){
		try {
			UserVO user = iuser.selectByCondition(" user_name='"+name+"' or user_code='"+name+"'");
			return user;
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
			return null;
		}
	}
	
}
